package com.lxl.securitypermission.config.custom;

import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

/**
 * 自定义授权异常，例如 403
 */
@Slf4j
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

  @Override
  public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException)
      throws IOException, ServletException {
    log.warn(accessDeniedException.getMessage());

    if (request.getMethod().equals("GET")) {
      String url = "/403";
      //1.调用HttpServletRequest的getRequestDispatcher()方法，调用时需要传入转发的地址;
      RequestDispatcher requestDispatcher = request.getRequestDispatcher(url);
      //2.调用HttpServletRequest的forward(request,response)方法进行请求的转发;
      requestDispatcher.forward(request, response);
    } else {
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("code", 1);
      jsonObject.put("message", "权限不足，无法执行！- 403");
      //让浏览器用utf8来解析返回的数据
      response.setHeader("Content-type", "application/json;charset=utf-8");
      response.setCharacterEncoding("UTF-8");//防止中文乱码
      response.getWriter().write(jsonObject.toJSONString());
    }
  }
}
